<template>
  <div class="temp-humidity-modal" v-if="visible" @click.self="closeModal">
    <div class="modal-content">
      <div class="modal-header">
        <h2>{{ title }} - 详细数据</h2>
        <button class="close-btn" @click="closeModal">×</button>
      </div>

      <div class="chart-container">
        <div class="chart-section">
          <h3>24小时{{ chartType === 'temperature' ? '温度' : '湿度' }}趋势</h3>
          <div class="chart-wrapper">
            <div ref="hourlyChart" class="echarts-chart"></div>
          </div>
        </div>

        <div class="chart-section">
          <h3>一周{{ chartType === 'temperature' ? '温度' : '湿度' }}趋势</h3>
          <div class="chart-wrapper">
            <div ref="weeklyChart" class="echarts-chart"></div>
          </div>
        </div>

        <div class="stats-section">
          <h3>统计数据</h3>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-label">当前值</div>
              <div class="stat-value">{{ currentValue }}{{ unit }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">今日最高</div>
              <div class="stat-value">{{ stats.todayMax }}{{ unit }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">今日最低</div>
              <div class="stat-value">{{ stats.todayMin }}{{ unit }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">平均</div>
              <div class="stat-value">{{ stats.average }}{{ unit }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';

export default {
  name: 'TempHumidityDetailChart',
  props: {
    visible: Boolean,
    chartType: String,
    currentValue: Number
  },
  emits: ['close'],
  setup(props, { emit }) {
    const hourlyChart = ref(null);
    const weeklyChart = ref(null);
    let hourlyChartInstance = null;
    let weeklyChartInstance = null;

    const title = computed(() => {
      return props.chartType === 'temperature' ? '空气温度' : '空气湿度';
    });

    const unit = computed(() => {
      return props.chartType === 'temperature' ? '°C' : '%RH';
    });

    // 模拟数据
    const stats = ref({
      todayMax: 0,
      todayMin: 0,
      average: 0
    });

    const generateMockData = () => {
      const baseValue = props.currentValue || (props.chartType === 'temperature' ? 25 : 60);
      const maxVariation = props.chartType === 'temperature' ? 15 : 30;

      // 生成24小时数据
      const hourlyData = [];
      const hourlyTimes = [];
      for (let i = 0; i < 24; i++) {
        const variation = (Math.sin(i * Math.PI / 12) + (Math.random() - 0.5) * 0.5) * maxVariation;
        const value = Math.round((baseValue + variation) * 10) / 10;
        hourlyData.push(value);
        hourlyTimes.push(`${i.toString().padStart(2, '0')}:00`);
      }

      // 生成一周数据
      const weeklyData = [];
      const weeklyTimes = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      for (let i = 0; i < 7; i++) {
        const variation = (Math.sin(i * Math.PI / 3.5) + (Math.random() - 0.5) * 0.3) * maxVariation;
        const value = Math.round((baseValue + variation) * 10) / 10;
        weeklyData.push(value);
      }

      // 计算统计数据
      stats.value = {
        todayMax: Math.max(...hourlyData).toFixed(1),
        todayMin: Math.min(...hourlyData).toFixed(1),
        average: (hourlyData.reduce((a, b) => a + b, 0) / hourlyData.length).toFixed(1)
      };

      return { hourlyData, hourlyTimes, weeklyData, weeklyTimes };
    };

    const initCharts = () => {
      if (!hourlyChart.value || !weeklyChart.value) return;

      const { hourlyData, hourlyTimes, weeklyData, weeklyTimes } = generateMockData();

      // 颜色配置
      const color = props.chartType === 'temperature' ? '#00ffd9' : '#FF6B6B';
      const areaColor = props.chartType === 'temperature'
        ? 'rgba(0, 255, 217, 0.1)'
        : 'rgba(255, 107, 107, 0.1)';

      // 24小时图表配置
      const hourlyOption = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: color,
          textStyle: {
            color: '#ffffff'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: hourlyTimes,
          axisLine: {
            lineStyle: {
              color: color
            }
          },
          axisLabel: {
            color: '#ffffff',
            fontSize: 10
          }
        },
        yAxis: {
          type: 'value',
          name: unit.value,
          nameTextStyle: {
            color: '#ffffff'
          },
          axisLine: {
            lineStyle: {
              color: color
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          },
          axisLabel: {
            color: '#ffffff'
          }
        },
        series: [
          {
            name: props.chartType === 'temperature' ? '温度' : '湿度',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              color: color,
              width: 3
            },
            itemStyle: {
              color: color
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: areaColor },
                { offset: 1, color: 'rgba(0, 255, 217, 0)' }
              ])
            },
            data: hourlyData
          }
        ]
      };

      // 周图表配置
      const weeklyOption = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: color,
          textStyle: {
            color: '#ffffff'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: weeklyTimes,
          axisLine: {
            lineStyle: {
              color: color
            }
          },
          axisLabel: {
            color: '#ffffff'
          }
        },
        yAxis: {
          type: 'value',
          name: unit.value,
          nameTextStyle: {
            color: '#ffffff'
          },
          axisLine: {
            lineStyle: {
              color: color
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          },
          axisLabel: {
            color: '#ffffff'
          }
        },
        series: [
          {
            name: props.chartType === 'temperature' ? '温度' : '湿度',
            type: 'bar',
            barWidth: '40%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: color },
                { offset: 1, color: color.replace(')', ', 0.5)') }
              ])
            },
            data: weeklyData
          }
        ]
      };

      // 初始化图表
      hourlyChartInstance = echarts.init(hourlyChart.value);
      hourlyChartInstance.setOption(hourlyOption);

      weeklyChartInstance = echarts.init(weeklyChart.value);
      weeklyChartInstance.setOption(weeklyOption);
    };

    const closeModal = () => {
      emit('close');
    };

    // 监听窗口大小变化
    const handleResize = () => {
      if (hourlyChartInstance) hourlyChartInstance.resize();
      if (weeklyChartInstance) weeklyChartInstance.resize();
    };

    onMounted(() => {
      window.addEventListener('resize', handleResize);
    });

    watch(() => props.visible, (newVal) => {
      if (newVal) {
        nextTick(() => {
          initCharts();
        });
      }
    });

    watch(() => props.currentValue, () => {
      if (props.visible) {
        initCharts();
      }
    });

    // 清理
    const cleanup = () => {
      if (hourlyChartInstance) {
        hourlyChartInstance.dispose();
        hourlyChartInstance = null;
      }
      if (weeklyChartInstance) {
        weeklyChartInstance.dispose();
        weeklyChartInstance = null;
      }
      window.removeEventListener('resize', handleResize);
    };

    return {
      title,
      unit,
      stats,
      hourlyChart,
      weeklyChart,
      closeModal,
      cleanup
    };
  },
  beforeUnmount() {
    this.cleanup();
  }
};
</script>

<style scoped>
.temp-humidity-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  backdrop-filter: blur(5px);
}

.modal-content {
  background: linear-gradient(135deg, #001c24 0%, #003543 100%);
  border: 2px solid #00ffd9;
  border-radius: 8px;
  width: 95%;
  height: 90%;
  padding: 20px;
  box-shadow: 0 0 50px rgba(0, 255, 217, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(0, 255, 217, 0.3);
}

.modal-header h2 {
  color: #00ffd9;
  margin: 0;
  font-size: 24px;
  text-shadow: 0 0 10px rgba(0, 255, 217, 0.5);
}

.close-btn {
  background: rgba(255, 107, 107, 0.2);
  border: 1px solid #ff6b6b;
  color: #ff6b6b;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  font-size: 24px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: rgba(255, 107, 107, 0.4);
  box-shadow: 0 0 15px rgba(255, 107, 107, 0.5);
}

.chart-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr auto;
  gap: 20px;
  height: calc(100% - 80px);
}

.chart-section {
  background: rgba(0, 28, 36, 0.6);
  border: 1px solid rgba(0, 255, 217, 0.2);
  border-radius: 6px;
  padding: 15px;
}

.chart-section h3 {
  color: #ffffff;
  margin: 0 0 15px 0;
  text-align: center;
  font-size: 16px;
}

.chart-wrapper {
  height: calc(100% - 40px);
}

.echarts-chart {
  width: 100%;
  height: 100%;
}

.stats-section {
  grid-column: 1 / -1;
  background: rgba(0, 28, 36, 0.6);
  border: 1px solid rgba(0, 255, 217, 0.2);
  border-radius: 6px;
  padding: 15px;
}

.stats-section h3 {
  color: #ffffff;
  margin: 0 0 15px 0;
  text-align: center;
  font-size: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
}

.stat-item {
  background: rgba(0, 255, 217, 0.1);
  border: 1px solid rgba(0, 255, 217, 0.3);
  border-radius: 6px;
  padding: 15px;
  text-align: center;
}

.stat-label {
  color: #ffffff;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  color: #00ffd9;
  font-size: 20px;
  font-weight: bold;
  text-shadow: 0 0 10px rgba(0, 255, 217, 0.5);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .chart-container {
    grid-template-columns: 1fr;
    grid-template-rows: 1fr 1fr auto;
  }

  .stats-section {
    grid-column: 1;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .modal-content {
    width: 98%;
    height: 95%;
    padding: 10px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>